package com.sjzd.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sjzd.server.constant.MailConstants;
import com.sjzd.server.mapper.MailLogMapper;
import com.sjzd.server.pojo.*;
import com.sjzd.server.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.parameters.P;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sjzd
 * @since 2021-02-21
 */
@Api(tags = "员工基础信息管理Controller")
@RestController
@RequestMapping("/emp")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;

    @ApiOperation("分页查询员工信息")
    @GetMapping("/page")
    public RespPageBean page(@RequestParam(value = "curPage",defaultValue = "1") Integer curPage,
                             @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                             Employee employee, String[] beginDateScope) {
        LocalDate[] bds = null;
        if (beginDateScope != null && beginDateScope.length == 2) {
            bds = new LocalDate[2];
            bds[0] = LocalDate.parse(beginDateScope[0]);
            bds[1] = LocalDate.parse(beginDateScope[1]);
        }
        return employeeService.page(employee, bds, curPage, pageSize);
    }

    @ApiOperation("获取所有民族")
    @GetMapping("/nation")
    public List<Nation> listNations() {
        return nationService.list();
    }

    @ApiOperation("获取职称")
    @GetMapping("/position")
    public List<Position> listPositions() {
        return positionService.list();
    }

    @ApiOperation("获取职级")
    @GetMapping("/joblevel")
    public List<Joblevel> listJoblevels() {
        return joblevelService.list();
    }

    @ApiOperation("获取政治面貌")
    @GetMapping("/politicsStatus")
    public List<PoliticsStatus> listPoliticsStatus() {
        return politicsStatusService.list();
    }

    @ApiOperation("获取部门")
    @GetMapping("/department")
    public List<Department> listDepartments() {
        return departmentService.getAllDepts();
    }

    @ApiOperation("获取新工号")
    @GetMapping("/workID")
    public String  workID() {
        return employeeService.getWorkID();
    }

    @ApiOperation("保存员工")
    @PostMapping("/")
    public RespBean add(@RequestBody Employee employee) {
        if (employee.getId() == null) {
            if (employeeService.save(employee)) {
                //数据库记录发送的消息
                String msgId = UUID.randomUUID().toString();
                MailLog mailLog = new MailLog();
                mailLog.setMsgId(msgId);
                mailLog.setEid(employee.getId());
                mailLog.setStatus(0);
                mailLog.setRouteKey(MailConstants.ROUTER_KEY);
                mailLog.setExchange(MailConstants.EXCHANGE_NAME);
                mailLog.setCount(0);
                mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
                mailLog.setCreateTime(LocalDateTime.now());
                mailLog.setUpdateTime(LocalDateTime.now());
                mailLogMapper.insert(mailLog);
                //发送信息
                rabbitTemplate.convertAndSend(MailConstants.EXCHANGE_NAME, MailConstants.ROUTER_KEY,employee,new CorrelationData(msgId));
                return RespBean.success("添加成功");
            } else {
                return RespBean.error("添加失败");
            }
        } else {
            return employeeService.updateById(employee) ? RespBean.success("更新成功") : RespBean.error("更新失败");
        }
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable Integer id) {
        if (employeeService.removeById(id)) {
            return RespBean.success("删除成功");
        } else {
            return RespBean.error("删除失败");
        }
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmployee(@RequestParam(name = "id", defaultValue = "") Integer id, HttpServletResponse response) {
        List<Employee> list = employeeService.getEmployee(id);
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode("员工表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @ApiImplicitParams({@ApiImplicitParam(name="file",value = "上传文件",dataType = "MultipartFile")})
    @PostMapping(value = "/import")
    public RespBean importEmployee(MultipartFile file) {
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nations = nationService.list();
        List<PoliticsStatus> politicsStatuses = politicsStatusService.list();
        List<Position> positions = positionService.list();
        List<Joblevel> joblevels = joblevelService.list();
        List<Department> departments = departmentService.list();

        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            if (employeeService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
            list = list.parallelStream().map(emp -> {
                Optional<Nation> nationOptional = nations.stream().filter(nation ->
                        nation.getName().equals(emp.getNation().getName())).findFirst();
                if (nationOptional.isPresent()) {
                    emp.setNationId(nationOptional.get().getId());
                } else {
                    throw new IllegalArgumentException("无此民族信息");
                }
                Optional<PoliticsStatus> politicsStatusOptional = politicsStatuses.stream().filter(politicsStatus ->
                        politicsStatus.getName().equals(emp.getPoliticsStatus().getName())).findFirst();
                if (politicsStatusOptional.isPresent()) {
                    emp.setPoliticId(politicsStatusOptional.get().getId());
                }
                Optional<Department> departmentOptional = departments.stream().filter(department ->
                        department.getName().equals(emp.getDepartment().getName())).findFirst();
                if (departmentOptional.isPresent()) {
                    emp.setDepartmentId(departmentOptional.get().getId());
                }
                Optional<Position> positionOptional = positions.stream().filter(position ->
                        position.getName().equals(emp.getPoliticsStatus().getName())).findFirst();
                if (positionOptional.isPresent()) {
                    emp.setPosId(positionOptional.get().getId());
                }
                Optional<Joblevel> joblevelOptional = joblevels.stream().filter(joblevel ->
                        joblevel.getName().equals(emp.getPoliticsStatus().getName())).findFirst();
                if (joblevelOptional.isPresent()) {
                    emp.setJobLevelId(joblevelOptional.get().getId());
                }
                emp.setWorkID(employeeService.getWorkID());
                return  emp;
            }).collect(Collectors.toList());
            employeeService.saveBatch(list);
            return RespBean.error("导入失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }
}
